import { useSearchParams } from "@/router/hooks";
import { useMenuData, useMenuSelected, useCacheMenus, useMenuActions, useSkipContainer } from "@/store/menuStore";
import { useUserToken } from "@/store/userStore";
import { isExternal } from "@/utils";
import React, { useMemo } from "react";
import { useEffect } from "react";
import { useRef } from "react";
import { useState } from "react";


//i18n
const ContainerPage = props => {
  let userToken = useUserToken();
  let cacheMenus = useCacheMenus();
  let modelMenus = useMenuData();
  let currentModel = useMenuSelected();
  let searchParams = useSearchParams();
  let iframeRef = useRef();
  let [showIframeUrl, setShowIframeUrl] = useState('');
  const { setCacheMenus } = useMenuActions()
  const skipContainer = useSkipContainer()

  const activeUrl = useMemo(() => {
    return searchParams.get('menuUrl') || currentModel?.url || currentModel?.path
  }, [searchParams, currentModel])

  useEffect(() => {
    urlChange()
  }, [activeUrl])

  const urlChange = () => {
    let url = activeUrl
    if (!url || cacheMenus.some(d => d.url === url)) return
    if (!currentModel?.id) {
      setCacheMenus(cacheMenus.concat({ ...currentModel, url }))
    } else {
      setCacheMenus(cacheMenus.concat({ url }))
    }
  }

  const getPermissionsCodes = (menu) => {
    let code = []
    let topMenu = modelMenus.find((d) => d.appId === menu.appId)
    let fun = (menu) => {
      if (menu.type == 2 || menu.type == 1) {
        // type 1是菜单，2是功能
        code.push(menu.code)
      }
      if (menu.children) {
        menu.children.forEach((item) => {
          fun(item)
        })
      }
    }

    topMenu && fun(topMenu)
    return code
  }

  const getDevUrl = (url) => {
    let urlObj = new URL(url)
    let devLs = import.meta.env.VITE_APP_XIANWAANG.split(',')
    if (devLs.find((s) => url.includes(s))) {
      return location.origin + urlObj.pathname
    }
    return url
  }
  const getIframeUrl = (current = {}) => {
    let iframeUrl = ''
    let modelUrl = current.url;

    // 解码菜单url
    let callbackUrl = modelUrl ? decodeURIComponent(modelUrl) : ''
    let andSyntax = modelUrl && callbackUrl.includes('?') ? '&' : '?' // 连接符 判断接&还是?

    // 如果没有前缀域名，则加上当前域名地址
    if (!isExternal(callbackUrl)) {
      callbackUrl = location.origin + '/' + callbackUrl.replace(/^\//g, '')
    } else if (import.meta.env.MODE === 'development') {
      callbackUrl = getDevUrl(callbackUrl)
    }

    if (current && current.id) {
      let code = current.code
      let pageName = current.name ? '&titleName=' + current.name : ''
      let permissions = getPermissionsCodes(current)
      permissions = permissions.length ? '&permissions=' + permissions.join(',') : []
      iframeUrl = `${callbackUrl}${andSyntax}isIFrame=true&token=${userToken}&code=${code}${pageName}${permissions}`
    } else if (modelUrl) {
      // 如果没有选中的菜单 ，则不管什么链接地址直接开发
      iframeUrl = `${callbackUrl}${andSyntax}token=${userToken}`
    }

    //todo，为大屏暂时写的，后面要删除
    if (iframeUrl.includes(`DataSet`)) {
      iframeUrl = iframeUrl + `&topUrl=${location.origin}/menus`
    }


    return iframeUrl


    // 对比两次iframe（去除time） 如果没有改变 则是需要刷新当前菜单
    if (showIframeUrl === iframeUrl) {
      setShowIframeUrl('')
    }

    setTimeout(() => {
      setShowIframeUrl(iframeUrl)  // isIFrame为了阻止permission.js中的重定向判断所添加
    }, 300)

    // 本地开发 AI 模型管理的路径
    // this.iframeUrl = `https://localhost:20410/${code}?token=${storage.get(ACCESS_TOKEN)}&form=app`
  }

  const iframeOnload = (e) => {
    const handle = window;
    // e.target.contentWindow.openWindow = (url) => {
    //   return handle.open(url)
    // }
  }

  return (
    <div style={{ height: '100%', width: '100%' }}>
      {cacheMenus.map(item => {
        return (
          <div key={item.url} style={{ height: '100%', width: '100%', display: activeUrl === item.url ? 'block' : 'none' }}>
            <iframe
              className="myIframe"
              src={getIframeUrl(item)}
              width="100%"
              ref={iframeRef}
              style={{
                height: '100%',
                padding: 0,
              }}
              frameBorder="0"
              marginHeight="0px"
              marginWidth="0px"
              scrolling="auto"
              allowFullScreen
              allow="microphone *;camera *"
              onLoad={iframeOnload}
            />
          </div>
        )

      })}

      {/* <iframe
        src={showIframeUrl}
        width="100%"
        ref={iframeRef}
        style={{
          height: '100%',
          padding: 0,
        }}
        frameBorder="0"
        marginHeight="0px"
        marginWidth="0px"
        scrolling="auto"
        allowFullScreen
        allow="microphone *;camera *" /> */}
    </div>
  );
};



export default ContainerPage;
